package com.thank.concurrency.samples.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * description: 演示ReentrantReadWriteLock
 *
 * @author xiefayang
 * 2018/7/12 10:27
 */
@Slf4j
public class LockExample3 {

    private final Map<String, Data> map = new TreeMap<>();

    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private final ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
    private final ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();

    public Data get(String key) {
        readLock.lock();
        try {
            return map.get(key);
        } finally {
            readLock.unlock();
        }
    }

    public Set<String> getAllKeys() {
        readLock.lock();
        try {
            return map.keySet();
        } finally {
            readLock.unlock();
        }
    }

    // 在没有任何读写锁的时候才可以进行写入操作
    public void put(String key, Data value) {
        writeLock.lock();;
        try {
            map.put(key, value);
        } finally {
            writeLock.unlock();
        }
    }

    private class Data{}
}

